package com.rybbaby.tss.front.tssClasses.service.imp;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.service.imp.BaseServiceImp;
import com.rybbaby.tss.front.tssClassAttendance.dao.ITssClassAttendanceDao;
import com.rybbaby.tss.front.tssClassAttendance.entity.TssClassAttendance;
import com.rybbaby.tss.front.tssClassChangeRecord.entity.TssClassChangeRecord;
import com.rybbaby.tss.front.tssClassChangeRecord.service.ITssClassChangeRecordService;
import com.rybbaby.tss.front.tssClasses.dao.ITssClassesDao;
import com.rybbaby.tss.front.tssClasses.entity.TssClasses;
import com.rybbaby.tss.front.tssClasses.service.ITssClassesService;
import com.rybbaby.tss.front.tssClassesLessons.entity.TssClassesLessons;
import com.rybbaby.tss.front.tssClassesLessons.service.ITssClassesLessonsService;
import net.sf.json.JSONSerializer;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;

/**
 * @author 雷春琼
 * @description 班级表数据库操作服务实现
 * @createDate 2017-08-09 下午11:50:14
 */
@Service
@Transactional
public class TssClassesServiceImp extends BaseServiceImp<TssClasses> implements ITssClassesService {

    @Autowired
    private ITssClassesDao dao;
    @Autowired
    private ITssClassesLessonsService tssClassesLessonsService;
    @Autowired
    private ITssClassChangeRecordService tssClassChangeRecordService;
    @Autowired
    private ITssClassAttendanceDao tsClassAttendanceDao;


    @Override
    public List<Map<String, Object>> batchQueryById(String id) {
        return dao.batchQueryById(id);
    }


    @Override
    public Boolean saveOrUpdate(TssClasses entity, String lessonsObject) throws Exception {
        Boolean bool = true;
        Boolean bool1 = true;
        String id = entity.getId();
        //解析课节json
        Gson gson = new Gson();
        List<TssClassesLessons> classesLessonsList = gson.fromJson(lessonsObject, new TypeToken<List<TssClassesLessons>>() {
        }.getType());
        //判断是否添加还是班级变动
        if (StringUtils.isNotBlank(id)) {
            //查询还有多少未上课课节可以变动
            Integer rowCount = this.tssClassesLessonsService.countCouldChangeLessons(id);
            List<TssClassChangeRecord> classChangeRecordList = new ArrayList<>();
            if (rowCount == classesLessonsList.size()) {
                //修改班级主体信息
                TssClasses destEntity = this.get(id);
                BeanUtils.copyProperties(entity, destEntity, "startDate", "endDate", "changeTime", "createTime", "updateTime");
                destEntity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                this.updateEntitiy(destEntity);
            }
            //修改课节信息
            for (TssClassesLessons classesLessons : classesLessonsList) {
                String lessonId = classesLessons.getId();
                String beforeJson = JSONSerializer.toJSON(this.mapJson(lessonId)).toString();
                Map<String, Object> lessonsMap = new HashedMap();
                lessonsMap.put("roomId", classesLessons.getRoomId());
                lessonsMap.put("classTime", classesLessons.getClassTime());
                lessonsMap.put("weekDay", classesLessons.getWeekDay());
                lessonsMap.put("startTime", classesLessons.getStartTime());
                lessonsMap.put("endTime", classesLessons.getEndTime());
                lessonsMap.put("adminUserId", classesLessons.getAdminUserId());
                Integer lessonsRowCount = this.tssClassesLessonsService.updateParameterById(lessonsMap, lessonId);
                if (lessonsRowCount == 0) {
                    return !bool;
                }
                String afterJson = JSONSerializer.toJSON(this.mapJson(lessonId)).toString();
                addChangeRecord(classChangeRecordList, lessonId, afterJson, beforeJson);
            }
            this.tssClassChangeRecordService.jdbcBatchSave(classChangeRecordList);
        } else {
            //保存班级信息
            entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
            entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            Serializable newId = this.save(entity);
            TssClasses classes = this.get(newId.toString());
            if (StringUtils.isBlank(newId)) {
                return !bool;
            }
            List<TssClassAttendance> tssClassAttendanceArrayList = new ArrayList<>();
            //保存课节信息
            for (TssClassesLessons classesLessons : classesLessonsList) {
                classesLessons.setClassIndexTime(classesLessons.getClassIndexTime());
                classesLessons.setStartTime(classes.getStartTime());
                classesLessons.setEndTime(classes.getEndTime());
                classesLessons.setClassId(newId.toString());
                classesLessons.setAdminUserId(classes.getEmpAdminUserId());
                classesLessons.setRoomId(classes.getRoomId());
                classesLessons.setCreateTime(new Timestamp(System.currentTimeMillis()));
                classesLessons.setVersion(0);
                classesLessons.setId(SequenceUtil.getUpperCaseUUID());
                classesLessons.setClassTime(classesLessons.getClassTime());
                classesLessons.setWeekDay(classesLessons.getWeekDay());
                classesLessons.setStatus(1);

                //保存班级考勤信息
                TssClassAttendance tssClassAttendance = new TssClassAttendance();
                tssClassAttendance.setId(SequenceUtil.getUpperCaseUUID());
                tssClassAttendance.setAttendanceStatus(1);
                tssClassAttendance.setClassId(classesLessons.getClassId());
                tssClassAttendance.setLessonsId(classesLessons.getId());
                tssClassAttendance.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                tssClassAttendanceArrayList.add(tssClassAttendance);
            }



            bool = this.tssClassesLessonsService.jdbcBatchSave(classesLessonsList);
            if (bool) {
                bool1 = tsClassAttendanceDao.jdbcBatchSave(tssClassAttendanceArrayList);
            }
            if (!bool1) {
                return !bool1;
            }

        }
        return bool;
    }

    @Override
    public Integer updateClassByIsBlockUp(String targetDateId, Boolean isBlockUp) {
        return dao.updateClassByIsBlockUp(targetDateId, isBlockUp);
    }

    @Override
    public Integer getExpendClassHour(String lessonId) {
        return dao.getExpendClassHour(lessonId);
    }

    @Override
    public PageBean attendancePageList(String notAttendance, int pageNo, int pageSize) {
        return dao.attendancePageList(notAttendance, pageNo, pageSize);
    }

    /**
     * 无条件查询所有信息
     */
    public List<TssClasses> getAllList() {
        return dao.loadAll(TssClasses.class);
    }

    /**
     * 根据ID查询List集合
     */
    public List<TssClasses> findListById(List<String> ids) {
        return dao.loadByMultipleId(TssClasses.class, ids);
    }

    /**
     * 添加班级变动信息
     *
     * @param lesson
     */
    private Map<String, Object> mapJson(String lesson) {
        Map<String, Object> map = new HashedMap();
        //查询班级课节变更之前信息
        TssClassesLessons tartgetLessons = this.tssClassesLessonsService.get(lesson);
        map.put("lessonInfo", tartgetLessons);
        //查看班级变更之前信息
        TssClasses beforeTargerClass = this.dao.get(TssClasses.class, tartgetLessons.getId());
        map.put("classInfo", beforeTargerClass);
        return map;
    }

    /**
     * 添加班级变动记录
     *
     * @param classChangeRecordList
     */
    private void addChangeRecord(List<TssClassChangeRecord> classChangeRecordList, String lesson, String afterJson, String beforeObject) {
        TssClassChangeRecord changeRecord = new TssClassChangeRecord();
        changeRecord.setBeforeJsonInfo(beforeObject);
        changeRecord.setAfterJsonInfo(afterJson);
        classChangeRecordList.add(changeRecord);
    }

    @Override
    public int getStudentCount(String classId) {
        return this.dao.getStudentCount(classId);
    }

    @Override
    public List<TssClasses> getStudentClasses(String studentId) {
        return this.dao.getStudentClasses(studentId);
    }

    @Override
    public Map<String, Object> verificationClass(String startDate, String endDate, String startTime, String endTime, String roomId, String weekDay, String empAdminUerId, String schoolId, Integer type) {
        return this.dao.verificationClass(startDate, endDate, startTime, endTime, roomId, weekDay, empAdminUerId, schoolId, type);
    }
}
